package com.itmk.student_select.controller;

import com.alibaba.fastjson.JSONObject;
import com.itmk.student_select.entity.StudentSelectParm;
import com.itmk.student_select.entity.StudentSelectVo;
import com.itmk.student_select.service.StudentSelectService;
import com.itmk.student_select.service.impl.StudentSelectServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/studentSelect.do")
public class StudentSelectServlet extends HttpServlet {
    private StudentSelectService studentSelectService = new StudentSelectServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("list")){
            list(req,resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取前端传递过来的参数
        int page = Integer.valueOf(req.getParameter("page"));
        int limit = Integer.valueOf(req.getParameter("limit"));
        String courseName = req.getParameter("courseName");
        //封装参数
        StudentSelectParm parm = new StudentSelectParm();
        parm.setCourseName(courseName);
        parm.setLimit(limit);
        parm.setPage(page);
        //调用service
        List<StudentSelectVo> list = studentSelectService.list(parm);
        //查询总条数
        int count = studentSelectService.getCount(parm);
        //封装返回数据格式
        JSONObject object = new JSONObject();
        object.put("code",0);
        object.put("data",list);
        object.put("msg","查询成功");
        object.put("count",count);
        //写回前端
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.print(object.toJSONString());
    }
}
